package com.swordliu.facebook.config.shiro;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.Cache;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * ShiroCredentialsMatcher
 * Created by SwordLiu on 2017-07-10.
 */
public class ShiroCredentialsMatcher extends HashedCredentialsMatcher {

    private Cache<String, AtomicInteger> passwordRetryCache;

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {

        //登录次数限制
        String username = (String) token.getPrincipal();
        //获取已经登录的次数
        AtomicInteger retryCount = passwordRetryCache.get(username);
        //如果是第一次登录，则创建一个新的AtomicInteger(原子操作Integer)
        if (null == retryCount) {
            retryCount = new AtomicInteger(0);
            passwordRetryCache.put(username, retryCount);
        }
        //如果登录尝试次数大于5次，则禁用一定时间
        if (retryCount.incrementAndGet() > 3) {
            throw new RuntimeException("登录尝试次数超3次了");
        }

        //执行登录凭证匹配，如果匹配成功，则移除登录次数的缓存
        boolean match = super.doCredentialsMatch(token, info);
        if (match) {
            passwordRetryCache.remove(username);
        }

        return match;
    }
}
